package com.itheima.controller;

import com.itheima.entity.User;
import com.itheima.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @PostMapping
//    @CachePut(cacheNames = "userCache",key = "#user.id") //这个user是方法参数传过来的,和形参名一样即可
//    @CachePut(cacheNames = "userCache",key = "#p0.id") //这个取到的是第一个参数（从p0开始）
    // #user.id   #p0.id   #p1.id   #root.args[0].id  都可以，但第一种方式最直观
    //@CachePut注解，来操作缓存
    @CachePut(cacheNames = "userCache",key = "#result.id") //这个result是返回值对象
    //key里面是： spring EL 即spring的表达式语言 SPEL
    //如果使用spring cache缓存数据，key的生成:userCache::key
    public User save(@RequestBody User user){
        userMapper.insert(user);
        return user;
    }

    @DeleteMapping
    @CacheEvict(cacheNames = "userCache",key = "#id") //删除对应缓存数据  //evict 依法驱逐，依法收回
    public void deleteById(Long id){
        userMapper.deleteById(id);
    }

	@DeleteMapping("/delAll")
    @CacheEvict(cacheNames = "userCache",allEntries = true)  //删除所有的key,value
    public void deleteAll(){
        userMapper.deleteAll();
    }

    @GetMapping
    @Cacheable(cacheNames = "userCache",key = "#id")
    public User getById(Long id){
        User user = userMapper.getById(id);
        return user;
    }

}
